package org.jeecg.modules.rental.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.iot.cache.EBikeCache;
import org.jeecg.modules.iot.model.EBikeLocation;
import org.jeecg.modules.iot.model.power.TaiPower;
import org.jeecg.modules.rental.entity.RentalEBike;
import org.jeecg.modules.rental.mapper.RentalEBikeMapper;
import org.jeecg.modules.rental.req.*;
import org.jeecg.modules.rental.resp.EBikeLocaltionResp;
import org.jeecg.modules.rental.resp.IotInfoResp;
import org.jeecg.modules.rental.resp.ManageEBikeResp;
import org.jeecg.modules.rental.resp.RentalEBikeResponse;
import org.jeecg.modules.rental.service.IRentalEBikeService;
import org.jeecg.modules.rental.service.impl.CtrlEBikeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 租车车辆信息
 * @Author: jeecg-boot
 * @Date: 2024-04-26
 * @Version: V1.0
 */
@Api(tags = "租车车辆信息")
@RestController
@RequestMapping("/rental/ebike")
@Slf4j
public class RentalEBikeController extends JeecgController<RentalEBike, IRentalEBikeService> {
    @Autowired
    private IRentalEBikeService rentalCarService;

    @Autowired
    private RentalEBikeMapper rentalEBikeMapper;

    @Autowired
    private EBikeCache eBikeCache;


    @Autowired
    private CtrlEBikeService ctrlEBikeService;
    /**
     * 分页列表查询
     * @param req
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "租车车辆信息-分页列表查询")
    @ApiOperation(value = "租车车辆信息-分页列表查询", notes = "租车车辆信息-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="rental/ebike/ebikelist")
    public Result<IPage<RentalEBike>> queryPageList(RentalEBike req, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest request) {
        QueryWrapper<RentalEBike> queryWrapper = QueryGenerator.initQueryWrapper(req, request.getParameterMap());
        Page<RentalEBike> page = new Page<>(pageNo, pageSize);
        IPage<RentalEBike> pageList = rentalCarService.selectJoinPage(page, queryWrapper);
        return Result.OK(pageList);
    }


    @ApiOperation(value = "租车车辆信息-分页列表查询", notes = "租车车辆信息-分页列表查询")
    @GetMapping(value = "/addcar")
    public Result<String> addcar(   HttpServletRequest request) {
        rentalCarService.addcar();
        return Result.OK("好了");
    }

    @ApiOperation(value="车辆位置列表查询", notes="车辆位置列表查询")
    @GetMapping(value = "/location-list")
    @PermissionData(pageComponent="rental/ebike/ebikelist")
    public Result<List<EBikeLocation>> locationList(RentalEBike req, HttpServletRequest request) {
        QueryWrapper<RentalEBike> queryWrapper = QueryGenerator.initQueryWrapper(req, request.getParameterMap());
        List<EBikeLocation> carLocationList = rentalCarService.selectLocationList(queryWrapper);
        return Result.OK(carLocationList);
    }

    @ApiOperation(value="车辆轨迹", notes="-分页列表查询")
    @PostMapping(value = "/track-list")
    public Result<String> trackList(@RequestBody EBikeTrackReq req) throws JsonProcessingException {
        String carTrackList = ctrlEBikeService.trackList(req, req.getCarCode());
        return Result.OK(carTrackList);
    }

//    @ApiOperation(value = "租车车辆信息-分页列表查询", notes = "租车车辆信息-分页列表查询")
//    @GetMapping(value = "/manageList")
//    @PermissionData(pageComponent="rental/ebike/ebikelist")
//    public Result<Page<RentalEBike>> manageList(RentalEBike req, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
//                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
//                                                HttpServletRequest request) {
//        QueryWrapper<RentalEBike> queryWrapper = QueryGenerator.initQueryWrapper(req, request.getParameterMap());
//        Page<RentalEBike> page = new Page<>(pageNo, pageSize);
//        return rentalCarService.selectManageDetailPage(page, queryWrapper);
//    }

    @ApiOperation(value = "租车车辆信息-分页列表查询", notes = "租车车辆信息-分页列表查询")
    @PostMapping(value = "/nearest")
    public Result<List<EBikeLocaltionResp>> queryNearestDevices(@Valid @RequestBody EBikeLocationReq carLocationReq) {
        Double latitude = carLocationReq.getLatitude();
        Double longitude = carLocationReq.getLongitude();
        Integer isLease = carLocationReq.getIsLease(); //  From request, filters results
        Integer range = 1000;

        //TODO 获取这个经纬度附近的所有车辆编号和对应经纬度

        //再根据车辆编号直接查询车辆数据,
        List<RentalEBike> eBikeList = new ArrayList<>();
        //赋值
        List<EBikeLocaltionResp> list = new ArrayList<>();
        eBikeList.stream().forEach(item->{
            EBikeLocaltionResp eBikeLocaltionResp = new EBikeLocaltionResp();
//            eBikeLocaltionResp.setLatitude();
//            eBikeLocaltionResp.setLongitude();
            eBikeLocaltionResp.setCarCode(item.getCarCode());
            eBikeLocaltionResp.setPlate(item.getPlate());
//            eBikeLocaltionResp.setIsLease(); //从缓存中获取租赁状态
            list.add(eBikeLocaltionResp);
        });
        return Result.ok(list);
    }

    /**
     * 添加
     *
     * @param rentalCar
     * @return
     */
    @AutoLog(value = "租车车辆信息-添加")
    @ApiOperation(value = "租车车辆信息-添加", notes = "租车车辆信息-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody RentalEBike rentalCar) {
        rentalCarService.add(rentalCar);
        return Result.OK("common.add.success");
    }


    @AutoLog(value = "车辆管理信息")
    @ApiOperation(value = "车辆管理信息", notes = "车辆管理信息")
    @GetMapping(value = "/manage-list")
    @PermissionData(pageComponent="rental/device/ebikelist")
    public Result<List<ManageEBikeResp>> manageList(ManageEBikeReq req, HttpServletRequest request) {
        RentalEBike rentalEBike = new RentalEBike();
        BeanUtils.copyProperties(req, rentalEBike);
        QueryWrapper<RentalEBike> queryWrapper = QueryGenerator.initQueryWrapper(rentalEBike, request.getParameterMap());
        List<ManageEBikeResp> list = rentalCarService.selectManageList(req, queryWrapper);
        log.info("数量:{}", list.size());
        return Result.ok(list);
    }

    @AutoLog(value = "租车车辆信息-编辑")
    @ApiOperation(value = "租车车辆信息-编辑", notes = "租车车辆信息-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody RentalEBike rentalCar) {
        rentalCarService.edit(rentalCar);
        return Result.OK("common.edit.success");
    }

    @AutoLog(value = "设置电子围栏")
    @ApiOperation(value = "设置电子围栏", notes = "设置电子围栏")
    @RequestMapping(value = "/set-fence", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> setFence(@RequestBody RentalEBike rentalCar) {
        rentalCarService.setFence(rentalCar);
        return Result.OK("common.edit.success");
    }

    @AutoLog(value = "更换中控")
    @ApiOperation(value = "更换中控", notes = "更换中控")
    @RequestMapping(value = "/swap", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> swap(@RequestBody SwapCarReq swapCarReq) {
        rentalCarService.swap(swapCarReq);
        return Result.OK("car.control.swap.success");
    }

    @AutoLog(value = "设置控制器")
    @ApiOperation(value = "设置控制器", notes = "设置控制器")
    @RequestMapping(value = "/setControl", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> setControl(@RequestBody SetControlReq setControlReq) {
        rentalCarService.setControl(setControlReq);
        return Result.OK("common.edit.success");
    }

    @AutoLog(value = "批量设置控制器")
    @ApiOperation(value = "批量设置控制器", notes = "批量设置控制器")
    @RequestMapping(value = "/batchSetControl", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> batchSetControl(@RequestBody SetControlReq setControlReq) {
        rentalCarService.batchSetControl(setControlReq);
        return Result.OK("common.edit.success");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "租车车辆信息-通过id删除")
    @ApiOperation(value = "租车车辆信息-通过id删除", notes = "租车车辆信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        rentalCarService.removeById(id);
        return Result.OK("common.delete.success");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "租车车辆信息-批量删除")
    @ApiOperation(value = "租车车辆信息-批量删除", notes = "租车车辆信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.rentalCarService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("common.delete.batch.success");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "租车车辆信息-通过id查询")
    @ApiOperation(value = "租车车辆信息-通过id查询", notes = "租车车辆信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<RentalEBike> queryById(@RequestParam(name = "id", required = true) String id) {
        RentalEBike rentalCar = rentalCarService.getById(id);
        if (rentalCar == null) {
            return Result.error("car.control.not.found", null);
        }
        return Result.OK(rentalCar);
    }



    @ApiOperation(value = "租车车辆信息-通过id查询", notes = "租车车辆信息-通过id查询")
    @GetMapping(value = "/queryIdBycode")
    public Result<RentalEBike> queryIdBycode(@RequestParam(name = "carCode", required = true) String carCode) {
        RentalEBike rentalCar = this.rentalCarService.getOne(new QueryWrapper<RentalEBike>()
                .eq("car_code", carCode));
        ;
        if (rentalCar == null) {
            return Result.error("car.control.not.found", null);
        }
        return Result.OK(rentalCar);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param rentalCar
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RentalEBike rentalCar) {
        return super.exportXls(request, rentalCar, RentalEBike.class, "租车车辆信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RentalEBike.class);
    }

    @ApiOperation(value = "新车辆验证", notes = "新车辆验证")
    @GetMapping(value = "/new-verify")
    public Result<RentalEBike> newVerify(@RequestParam(name = "code", required = true) String code) {
        return rentalCarService.newVerify(code, false);
    }

    @ApiOperation(value = "编辑自编号", notes = "编辑自编号")
    @GetMapping(value = "/edit-customcode")
    public Result<RentalEBike> editCustomCode(
            @RequestParam(name = "ebikeId", required = true) Long ebikeId,
            @RequestParam(name = "customCode", required = true) String customCode) {
        rentalCarService.editCustomCode(ebikeId, customCode);
        return Result.OK();
    }


    @ApiOperation(value="终端上线临时-通过id查询", notes="终端上线临时-通过id查询")
    @RequestMapping(value = "/queryIotById", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<List<RentalEBike>> queryIotById(@RequestBody RentalEBike rentalEBike) {
        LambdaQueryWrapper<RentalEBike> iotTerminalTempLambdaQueryWrapper   = new LambdaQueryWrapper<>();
        iotTerminalTempLambdaQueryWrapper.eq(RentalEBike::getCarCode,rentalEBike.getCarCode());
        List<RentalEBike> iotTerminalTemps=rentalEBikeMapper.listNoTenant(iotTerminalTempLambdaQueryWrapper);
        return Result.OK(iotTerminalTemps);
    }

    @ApiOperation(value = "通过编号获取车辆列表", notes = "通过编号获取车辆列表")
    @GetMapping(value = "/info/{code}")
    public Result<List<RentalEBike>> info(@PathVariable(name = "code") String code) {
        List<RentalEBike> list = rentalCarService.listByCode(code);
        return Result.OK(list);
    }

    @ApiOperation(value = "获取iot信息", notes = "获取iot信息")
    @GetMapping(value = "/iot-info/{iotCode}")
    public Result<IotInfoResp> iotInfo(@PathVariable(name = "iotCode", required = true) String iotCode) {
        IotInfoResp iotInfoResp = rentalCarService.iotInfo(iotCode);
        return Result.OK(iotInfoResp);
    }

    @ApiOperation(value = "电单车组装", notes = "电单车组装")
    @PostMapping(value = "/assemble")
    public Result assemble(@Valid @RequestBody AssembleReq assembleReq) {
        rentalCarService.assemble(assembleReq);
        return Result.OK();
    }

    @ApiOperation("根据车辆编号查询车辆信息")
    @GetMapping("/carList")
    public Result<IPage<RentalEBikeResponse>> getCarList(
            @RequestParam(value = "carCode", required = false) String carCode,
            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, // 分页页码，默认第1页
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize // 每页大小，默认10条
    ) {
        try {
            // 构建查询条件
            QueryWrapper<RentalEBike> queryWrapper = new QueryWrapper<>();
            if (carCode != null && !carCode.isEmpty()) {
                queryWrapper.eq("car_code", carCode); // 根据车辆编号查询
            }

            // 分页对象
            Page<RentalEBike> page = new Page<>(pageNo, pageSize);

            // 查询数据库中的车辆信息（分页）
            IPage<RentalEBike> carPage = rentalCarService.page(page, queryWrapper);

            // 转换分页结果为自定义返回对象
            IPage<RentalEBikeResponse> responsePage = carPage.convert(car -> {
                RentalEBikeResponse response = new RentalEBikeResponse();
                response.setCarCode(car.getCarCode()); // 车辆编号
                TaiPower taiPower = eBikeCache.getVehiclePower(car.getCarCode());
                response.setPower(taiPower != null ? taiPower.getRPowCap() : null); // 电池电量
                response.setOdo(car.getSpeed()); // 总里程
                String onlineStatus = eBikeCache.getVehicleOnlineStatus(car.getCarCode());
                response.setStatus(onlineStatus); // 在线状态 online/offline
                return response;
            });

            return Result.OK(responsePage);
        } catch (Exception e) {
            log.error("根据车辆编号查询车辆信息失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}
